package liwen.zhao.service;

import liwen.zhao.common.jd.pojo.Seckill;
import liwen.zhao.common.jd.vo.SysResult;
import liwen.zhao.mappers.SecKillMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SecKillServiceImpl implements SecKillService {
    @Autowired
    private SysResult sysResult;
    @Autowired
    private SecKillMapper secKillMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public SysResult addSecKill(Seckill seckill) {
        try {
            secKillMapper.add(seckill);
            //将商品库存在Redis进行记录
            redisTemplate.opsForValue().set("shop"+seckill.getId(),seckill.getScount()+"");
            sysResult.setStatus(200);
        } catch (Exception e) {
            e.printStackTrace();
            sysResult.setStatus(e,500);
        }
        return sysResult;
    }
    
    @Override
    public SysResult getThree() {
        try {
            List<Seckill> secKillList=secKillMapper.getThree();
            sysResult.setStatus(200);
            sysResult.setData(secKillList);
        } catch (Exception e) {
            e.printStackTrace();
            sysResult.setStatus(e,500);
        }
        return sysResult;
    }
    
    /**
     * 描述的具体实现
     * @param uid 用户id
     * @param sid 秒杀id
     * @return
     */
    @Override
    public SysResult doSeckill(int uid, int sid) {
        int scount = Integer.parseInt(redisTemplate.opsForValue().get("shop" + sid));
        if(scount<=0){
            sysResult.setStatus(500);
            sysResult.setMsg("秒杀失败，库存不足！");
            return sysResult;
        }
        //商品库存减1
        redisTemplate.opsForValue().increment("shop" + sid,-1);
        sysResult.setStatus(200);
        sysResult.setMsg("秒杀成功！");
        String msg=uid+"|"+sid;
        sysResult.setData(msg);
        rabbitTemplate.convertAndSend("seckillEX","seckill",msg);
        return sysResult;
    }
    //监听队列
    @RabbitListener(queues = "seckillQ")
    public void seckillCustom(String msg){
        System.err.println("秒杀记录："+msg+"\t"+"模拟id为"+msg.split("\\|")[1]+"的秒杀库存减1");
    }
}
